package com.bq.gametrade.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.text.format.Time;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Feel on 2017/1/3.
 */

public class SmsReceiver extends BroadcastReceiver{

    private String strContent;
    private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";

    private Handler mHandler;
    private Context mContext;

    public SmsReceiver(Context context,Handler handler){
        this.mContext = context;
        this.mHandler = handler;

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Object[] objs = (Object[]) intent.getExtras().get("pdus");
        for (Object obj : objs) {
            byte[] pdu = (byte[]) obj;
            SmsMessage sms = SmsMessage.createFromPdu(pdu);
            // 短信的内容
            String message = sms.getMessageBody();
            // 短息的手机号。。+86开头？
            String from = sms.getOriginatingAddress();
            Time time = new Time();
            time.set(sms.getTimestampMillis());
            String time2 = time.format3339(true);
            strContent = from + "   " + message;
//            handler.sendEmptyMessage(1);
            if (!TextUtils.isEmpty(from)) {
                String code = patternCode(message);
                if (!TextUtils.isEmpty(code)) {
                    strContent = code;
////                    handler.sendEmptyMessage(1,);
//                    Message messageCode = new Message();
//                    messageCode.arg1 = 2;
//                    messageCode.what = Integer.parseInt(code);
//                    mHandler.sendMessage(messageCode);

                    mHandler.obtainMessage(1, code).sendToTarget();
                }
            }
        }

    }

    /**
     * 匹配短信中间的6个数字（验证码等）
     *
     * @param patternContent
     * @return
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }
}
